//
//  ArrayListString.c
//  LC3Compiler
//
//  Created by Anthony Sierra on 6/1/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//
#include "ArrayListString.h"

void initializeArrayList(ArrayList * list)
{   
    assert(list != NULL);
    
    list->items = (char **)malloc(10 * sizeof(char));
    list->listSize = 0;
    list->arraySize = 10;
    
}
void destroyArrayList(ArrayList * list)
{   
    assert(list != NULL);
    
    free(list->items);
    
}
int getSize(const ArrayList * list)
{   
    assert(list != NULL);
    
    return list->listSize;
    
}
char* getItem(const ArrayList * list, int index)
{  
    assert(list != NULL);
    assert(index >= 0 && index < list->listSize);
    
    return list->items[index];
    
}
void setItem(ArrayList * list, int index, char* word)
{   
    assert(list != NULL);
    assert(index >= 0 && index < list->listSize);
    
    list->items[index] = word;
    
}
void addItemToEndOfArrayList(ArrayList * list, char *value)
{   
    int i;
    char *tmp;
    
    assert(list != NULL);
    
    if (list->listSize == list->arraySize)
    {
        // No more room in the array, so get a bigger array.
        tmp = (char *)malloc(list->arraySize * 2 * sizeof(char));
        assert(tmp != NULL);
        for (i = 0; i < list->arraySize; ++i)
            tmp[i] = list->items[i];
        free(list->items);
        list->items = tmp;
        list->arraySize *= 2;
    }
    
    // Store the new item in the array.
    list->items[list->listSize] = value;
    ++list->listSize;
    
}
void addItemBeforeItem(ArrayList * list, int index, char *value)
{
    int i;
    char *tmp;
    
    assert(list != NULL);
    assert(index >= 0 && index < list->listSize);
    
    if (list->listSize == list->arraySize)
    {
        // No more room in the array, so get a bigger array.
        tmp = (char *)malloc(list->arraySize * 2 * sizeof(char));
        assert(tmp != NULL);
        for (i = 0; i < list->arraySize; ++i)
            tmp[i] = list->items[i];
        free(list->items);
        list->items = tmp;
        list->arraySize *= 2;
    }
    
    // Move all items following the new item one element to the right.
    for (i = list->listSize; i > index; --i)
        list->items[i] = list->items[i-1];
    
    // Store the new item in the array.
    list->items[index] = value;
    ++list->listSize;
}
